package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author tongchen
 * @create 2023-01-25 17:12
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
    @PostMapping
    public R<String> save(@RequestBody Category category,HttpServletRequest request){
        Long emplpyee1 =(Long) request.getSession().getAttribute("employee");
        log.info(emplpyee1.toString());
        category.setCreateUser(emplpyee1);
        category.setUpdateUser(emplpyee1);
        categoryService.save(category);
        log.info(category.toString());
        return R.success("新增分类成功");
    }
    //创建分页构造器
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //设置分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //创建条件构造器和排序
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        //进行分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }
    @DeleteMapping()
    public R<String> delete( Long ids){
       return  categoryService.delete(ids);
    }
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
    //添加条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType()!=null, Category::getType, category.getType());
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return   R.success(list);
    }
}
